package com.asiainfo.kbisheet.util.yunnan;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;

/**
 * 云南移动的user_id加密算法
 * @author kyunra
 *
 */
public class OADecrypt {
	private static String n = "4DCCD7F7E69FE85ED02E7ABA17BA21C89AEFA4F75FD19BC8DA6538CA3E416C6D9135064BE997C1B40ED12A47A09E4872F21CBEF2FBDCE9247F2D31836495D7665C15B39132188B5B4BF9B056D539C704D138856CBFE0C8D115E46BDA8CD61E3035ADD5B72161ECFFBC87B2DEE3C23748DB49F26D137919FC356FCCC4E22A07F1";
	private static String d = "385BC2BB674AC1772591F5FFA6BE8448A0CC2711B84CCC70549CECE5BCF181CD615A2B0484E415430D54C22EFF108A65123476B2E876E0413B0B8F09A2ACD54B197F79C8BCA4E766C6CE880BED1AAC0C991DEE8A7AB12D41D92F0B6DC951BD9875BEF14F6EBC4F7F4D0AB0535F5CFE49A0C6B16C4137CFC0D6970E9488E2C69D";
	private static BigInteger e = BigInteger.valueOf(65537);

	// 加密
	public static String encrypt(String encryStr)
			throws UnsupportedEncodingException {
		final String tmp = toUnicode(encryStr);
		byte ptext[] = tmp.getBytes("UTF8");
		BigInteger m = new BigInteger(ptext);
		BigInteger c = m.modPow(Hex2Dec(d), Hex2Dec(n));
		return c.toString(16);
	}

	// 解密
	public static String decrypt(String encryptNumb) {
		BigInteger c = new BigInteger(encryptNumb, 16);
		BigInteger m = c.modPow(e, Hex2Dec(n));
		byte[] mt = m.toByteArray();
		StringBuffer str = new StringBuffer();
		for (int i = 0; i < mt.length; i++) {
			str.append((char) mt[i]);
		}
		final String tmp = str.toString();

		return decodeUnicode(tmp);
	}

	 private static String decodeUnicode(String dataStr)
     {
         int start = 0;
         int end = 0;
         StringBuilder buffer = new StringBuilder();
         while (start > -1)
         {
             end = dataStr.indexOf("\\u", start + 2);
             String charStr = "";
             if (end == -1)
             {
                 charStr = dataStr.substring(start + 2, dataStr.length());
             }
             else
             {
                 charStr = dataStr.substring(start + 2, end);
             }            
             
             char letter = (char)Integer.parseInt(charStr, 16);
             buffer.append(letter);
             start = end;
         }
         return buffer.toString();
     }

	private static String toUnicode(String strText)
			throws UnsupportedEncodingException {
		char c;
		String strRet = "";
		int intAsc;
		String strHex;
		for (int i = 0; i < strText.length(); i++) {
			c = strText.charAt(i);
			intAsc = (int) c;
			if (intAsc > 128) {
				strHex = Integer.toHexString(intAsc);
				strRet += "\\u" + strHex;
			}
			else {
				strRet += "\\u" + Integer.toHexString(c);
			}
		}
		return strRet;
	}

	public static BigInteger Hex2Dec(String n) {
		return new BigInteger(n, 16);
	}

}
